package fragments;

import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import utils.AppPreferences;
import utils.BitmapLoader;
import utils.CashData;
import utils.UserInfo;
import activities.PhotoActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import apies.VkApi;

import com.mga.wheelcommunity.R;

public class UserFragment extends Fragment {
	String photoUrl;
	TextView userBdTv;
	TextView userCityTv;
	TextView userNameTv;
	TextView userPhotoLabel, userCityLabel;
	ImageView userPhotoImageView;
	Bitmap bitmap;
	UserInfo user = UserInfo.getInstance();
	ProgressDialog progressDialog;
	static Context _context;
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.user_fragment, container, false);
		
		userBdTv = (TextView)view.findViewById(R.id.textViewUserBd);
		userCityTv = (TextView)view.findViewById(R.id.textViewUserCity);
		userNameTv = (TextView)view.findViewById(R.id.textViewUserName);
		userPhotoImageView = (ImageView)view.findViewById(R.id.imageViewUserPic);
		userPhotoLabel = (TextView)view.findViewById(R.id.tvUserBirthday);
		userCityLabel = (TextView)view.findViewById(R.id.tvUserCity);
		
		setViewsVisibility(View.INVISIBLE);
		
		try{
		VkApi api = new VkApi(AppPreferences.getTokenValue(_context), 
				  AppPreferences.getUserIdValue(_context));
		if(CashData.getInstance().containsKey(CashData.USER_INFO)) {
			user = CashData.getInstance().getUserInfo();
			userNameTv.setText(user.name);
			userBdTv.setText(user.birthday);
			userCityTv.setText(user.city);
			userPhotoImageView.setImageBitmap(user.photo);
			setViewsVisibility(View.VISIBLE);
			Log.d("UserFragment", "Data loaded from cash");
		} else 
			getDataFromJson(api);
		
		userPhotoImageView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent();
				i.putExtra("photo_max_orig", user.bigPhotoUrl);
				i.setClass(_context, PhotoActivity.class);
				startActivity(i);
			}
		});
		
		}catch(NullPointerException e) {
			Log.d("Exception", "NullPointerException: you should send Context "
					+ "via static method UserFragment.setContext.");
		}
		
		return view;
	}
	
	
	public static void setContext(Context context) {
		_context = context;
	}
	
	private void getDataFromJson(final VkApi api) {
		new AsyncTask<Void, Void, Void>() {
			
			@Override
			protected void onPreExecute() {
				progressDialog = new ProgressDialog(_context);
				progressDialog.setMessage("Loading...");
				progressDialog.show();
			};

			@Override
			protected Void doInBackground(Void... params) {
				try {
					JSONObject json = new JSONObject(api.getUsers());
					JSONArray response = json.getJSONArray("response");
					for (int i = 0; i < response.length(); i++) {
						JSONObject user_info = (JSONObject) response.get(i);
						photoUrl = user_info.getString("photo_100");
						user.bigPhotoUrl = user_info.getString("photo_max_orig");
						user.name = user_info.getString("first_name") + " " 
											+ user_info.getString("last_name");
						user.birthday = user_info.getString("bdate");
						user.city = api.getCities(user_info.getString("city"));
					}
					JSONObject cities = new JSONObject(user.city);
					response = cities.getJSONArray("response");
					for (int i = 0; i < response.length(); i++) {
						JSONObject city = (JSONObject) response.get(i);
						user.city = city.getString("name");
					}
					Log.d("city", user.city);
				} catch (JSONException e) {
					Log.d("JSONException", e.toString());
					e.printStackTrace();
				}
				return null;
			}
			
			@Override
			protected void onPostExecute(Void result) {
				userNameTv.setText(user.name);
				userBdTv.setText(user.birthday);
				userCityTv.setText(user.city);
				
				BitmapLoader loadBitmap = new BitmapLoader(userPhotoImageView);
				try{
					bitmap = loadBitmap.execute(photoUrl).get();
					user.photo = bitmap;
				}catch(Exception ex) {
					Log.d("Execution exception: ", ex.toString());
				} 
				
				CashData.getInstance().setUserInfo(user);
				
				setViewsVisibility(View.VISIBLE);
				
				progressDialog.dismiss();
			};
			
		}.execute();
		
	}
	
	private void setViewsVisibility(int visibility) {
		userBdTv.setVisibility(visibility);
		userCityTv.setVisibility(visibility);
		userNameTv.setVisibility(visibility);
		userPhotoImageView.setVisibility(visibility);
		userPhotoLabel.setVisibility(visibility);
		userCityLabel.setVisibility(visibility);
	}
	
}
